package com.nl.web.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;

/**
 * 导出文件工具类 .
 *
 * @author xht.
 * @createTime 2021年10月07日 15:21:00
 */
@Slf4j
public class ExportUtil {

    public static void easyExcelExport(HttpServletResponse response, final String fileName, Function<OutputStream,Void> function) {
        try {
            //设置 水平居中
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String outFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + outFileName);
            // 这里需要设置不关闭流
            function.apply(response.getOutputStream());
        } catch (IOException e) {
            log.info("导出文件失败：{}", e);
        }
    }


}
